package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.api.ISysOrg;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.TimeUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.enums.FlowStatusEnum;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.*;
import com.ccp.dev.qbdms.service.*;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.util.SysRoleUtil;
import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.TaskOpinion;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import com.ccp.dev.workflow.service.TaskOpinionService;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 质量管理体系 信息操作处理控制器
 *
 * @author 王明亮
 * @date 2020-05-12 10:39:53
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "质量管理体系")
@RequestMapping("/qbdms/wQbdQualitymanage")
public class WQbdQualitymanageController extends SysBaseController {
    @Resource
    private WQbdQualitymanageService wQbdQualitymanageService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private WQbdFalSuperviseService wQbdFalSuperviseService;
    @Resource
    private WQbdAccordingStandardService wQbdAccordingStandardService;
    @Resource
    private WQbdStandardClauseService wQbdStandardClauseService;
    @Resource
    private WQbdSubStandardClauseService wQbdSubStandardClauseService;
    @Value(value = "${service.customProcessName}")
    private boolean customProcessName = true;
    @Resource
    private WQbdQualitymanageSuService wQbdQualitymanageSuService;
    @Resource
    private TaskOpinionService taskOpinionService;
    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-05-12 10:39:53
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到质量管理体系首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        // 配置列相关
        wCustomColumnsService.addCustomCols(request);
        // 当前登录用户
        String currentUserId = ContextUtil.getCurrentUserId();
        // 当前登录组织
        SysOrg currentOrg = (SysOrg) ContextUtil.getCurrentOrg();
        // 子组织转数据字典
        List<Dictionary> originOrgList = extendSysOrgService.getSubordinateUnits();
        // 二级单位部署时要求另加上本单位
        if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(BaseUtil.getCurrentSystemLevel())) {
            if (originOrgList.stream().noneMatch(dictionary -> currentOrg.getCode().equals(dictionary.getItemValue()))) {
                Dictionary dictionary = new Dictionary();
                dictionary.setItemName(currentOrg.getOrgName());
                dictionary.setItemValue(currentOrg.getCode());
                originOrgList.add(dictionary);
            }
        }
        modelMap.put("currentUserId", currentUserId);
        modelMap.put("originOrgList", JSON.toJSONString(originOrgList));
        modelMap.put("currentSystemLevel", BaseUtil.getCurrentSystemLevel());
        // 依据标准
        List<WQbdAccordingStandard> accordingStandards = wQbdAccordingStandardService.queryList(null);
        modelMap.put("accordingStandards", JSON.toJSONString(accordingStandards));
        modelMap.put("researchRoomList", JSON.toJSONString(sysOrgService
                .querySubSysOrgBySupOrgIdNoChild(sysOrgService.getSysOrgByOrgCode("wrj").getOrgId())));
        //判断是否质量综合助理员
        boolean isAdd=false;
        SysRole currentRole = SysRoleUtil.getCurrentRole(request);
        if(currentRole.getAlias().equals("bpm_zlzhzly")){
            isAdd=true;
        }
        List<Dictionary> deptList = new ArrayList<>();
        // 检索条件【单位】：
        if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(BaseUtil.getCurrentSystemLevel())) {
            // 组织树中二级租户节点
            List<Dictionary> originOrgToDicList = extendSysOrgService.getSubordinateUnits();
            // 二级单位显示本单位以及所属三级单位
            if (originOrgToDicList.stream().noneMatch(dictionary -> currentOrg.getCode().equals(dictionary.getItemValue()))) {
                Dictionary dictionary = new Dictionary();
                dictionary.setItemName(currentOrg.getOrgName());
                dictionary.setItemValue(currentOrg.getCode());
                originOrgToDicList.add(dictionary);
            }
            deptList = originOrgToDicList;
        } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(BaseUtil.getCurrentSystemLevel())) {
            // 三级单位默认本单位
            Dictionary dictionary = new Dictionary();
            dictionary.setItemName(currentOrg.getOrgName());
            dictionary.setItemValue(currentOrg.getCode());
            deptList.add(dictionary);
        }
        modelMap.put("deptList", JSON.toJSONString(deptList));
        modelMap.put("isadd",isAdd);
        return "wQbdQualitymanage/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-12 10:39:53
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询质量管理体系", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照审核时间倒序排列,审核时间相同的情况下按创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "f_audittime");
            queryFilter.addFilter("orderSeq", "desc");
            queryFilter.addFilter("orderField1", "createtime");
            queryFilter.addFilter("orderSeq1", "desc");
        }
        // 添加通用查询条件
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdQualitymanage> pageDatas = wQbdQualitymanageService.queryList(queryFilter);
        String currentOrgId = ContextUtil.getCurrentOrgId();
        SysOrg sysOrgById = sysOrgService.getSysOrgById(currentOrgId);
        if (!sysOrgById.getCode().equals("1734")){
            queryFilter.remove("belongdeptname");
            pageDatas =  wQbdQualitymanageService.queryListBySu(queryFilter);
        }
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
//        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        ZhiLiangConst.isDataAllowEditByFlowStatus(pageDatas);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-05-12 10:39:53
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到质量管理体系新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        if (StringUtils.isNotBlank(id)) {
            WQbdQualitymanage wQbdQualitymanage = wQbdQualitymanageService.getOneById(id);
            modelMap.put("flowStatus", wQbdQualitymanage.getFlowStatus());
        }
        // 当前组织
        SysOrg sysOrg = (SysOrg) ContextUtil.getCurrentOrg();
        // 受审单位(注：受审单位理论上只有新增时才需要传，但是如果只在新增时传，编辑的时候页面会报错，因此提到if外面，这个问题以后直接略过，不要再看了)
        modelMap.put("unit", JSON.toJSONString(sysOrg));
        // 当前登录用户所在组织的下属部门
        Map<String, String> map = new HashMap<>(16);
        String orgId = sysOrg.getOrgId();
        map.put("ISTENANT", "0");
        map.put("ORGSUPID", orgId);
        List<Map> sysOrgList = wQbdFalSuperviseService.getOrg(map);
        // 受审核部门
        List<Dictionary> dicList = new ArrayList<>();
        for (Map sysOrgMap : sysOrgList) {
            Dictionary dictionary = new Dictionary();
            dictionary.setItemName(String.valueOf(sysOrgMap.get("ORGNAME")));
            dictionary.setItemValue(String.valueOf(sysOrgMap.get("CODE")));
            dicList.add(dictionary);
        }
        modelMap.put("depts", JSON.toJSONString(dicList));
        // 依据标准
        List<WQbdAccordingStandard> accordingStandards = wQbdAccordingStandardService.queryList(null);
        modelMap.put("accordingStandards", JSON.toJSONString(accordingStandards));
        modelMap.put("researchRoomList", JSON.toJSONString(sysOrgService
                .querySubSysOrgBySupOrgIdNoChild(sysOrgService.getSysOrgByOrgCode("wrj").getOrgId())));
        //青年助理为true  质量综合助理
        SysRole currentRole = SysRoleUtil.getCurrentRole(request);
        String alias = currentRole.getAlias();
        if (alias.equals("bpm_zlzhzly")){
            modelMap.put("zlzhzly",true);
        }else{
            modelMap.put("zlzhzly",false);
        }
        if (alias.equals("bpm_qnzl")){
            modelMap.put("qnzl",true);
        }else{
            modelMap.put("qnzl",false);
        }
        String code = ((SysOrg) ContextUtil.getCurrentOrg()).getCode();
        map.put("orgCode",code);


        return "wQbdQualitymanage/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdQualitymanage 保存的对象
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-12 10:39:53
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存质量管理体系数据", detail = "<#if isAdd>新增<#else>编辑</#if>质量管理体系数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdQualitymanage wQbdQualitymanage ,HttpServletRequest request) {
        String id = wQbdQualitymanage.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            //新增操作
            //新增数据前生成随机Id
            wQbdQualitymanage.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdQualitymanage);
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
            if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                wQbdQualitymanage.setReportStatus(ZhiLiangConst.HOSPITAL_INTERNALAPPROVAL_THEAPPROVALISPENDING);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                wQbdQualitymanage.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }
            wQbdQualitymanage.setFlowStatus(FlowStatusEnum.NOT_SUBMIT.getValue());
            result = wQbdQualitymanageService.add(wQbdQualitymanage);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdQualitymanage);
            result = wQbdQualitymanageService.update(wQbdQualitymanage,request);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdQualitymanageService.getOneById(id), wQbdQualitymanage));
        }
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        Map<String,Object> idMap= Maps.newHashMap();
        idMap.put("id",wQbdQualitymanage.getId());
        return result > 0 ? getResultDataSuccess("save.success",idMap) : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-05-12 10:39:53
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到质量管理体系详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        String hideCancelBtn = RequestUtil.getString(request, "hideCancelBtn");
        modelMap.put("hideCancelBtn", hideCancelBtn);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("runId", runId);
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        WQbdQualitymanage wQbdQualitymanage = wQbdQualitymanageService.getOneById(id);
        modelMap.put("flowStatus", wQbdQualitymanage.getFlowStatus());
        return "wQbdQualitymanage/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-12 10:39:53
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询质量管理体系的一条数据", detail = "根据主键id查询质量管理体系的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdQualitymanage wQbdQualitymanage = wQbdQualitymanageService.getOneById(id);
        List<WQbdQualitymanageSu> wQbdQualityRewardsMsgSubList = wQbdQualitymanageSuService.getListByRefId(id);
        //根据部门显示子表的数据
        String code = ((SysOrg) ContextUtil.getCurrentOrg()).getCode();
        //如果不是无人机室或者根组织则进行数据筛选
        if (!code.equals("1734")&&!code.equals("wrj")){
            ZhiLiangConst.showWQbdQualitymanageSu(wQbdQualityRewardsMsgSubList,code);
        }
        wQbdQualitymanage.setwQbdQualitymanageSuList(wQbdQualityRewardsMsgSubList);
        if (null == wQbdQualitymanage) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wQbdQualitymanage);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-12 10:39:53
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除质量管理体系数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) throws Exception{
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdQualitymanage wQbdQualitymanage = wQbdQualitymanageService.getOneById(key);
            if(!FlowStatusEnum.getEnumByValue(wQbdQualitymanage.getFlowStatus()).isDel()){
                return fail("删除失败！不允许删除流程未结束数据！");
            }
            if (!userId.equals(wQbdQualitymanage.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(wQbdQualitymanage.getReportStatus()) && !ZhiLiangConst.NOESCALATIONREQUIRED.equals(wQbdQualitymanage.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdQualitymanage.getReportStatus()) && !ZhiLiangConst.HOSPITAL_INTERNALAPPROVAL_THEAPPROVALISPENDING.equals(wQbdQualitymanage.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报、无需上报和院内待审批的数据");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        //流程实例删除
        for (String key : ids) {
            WQbdQualitymanage wQbdQualitymanage = wQbdQualitymanageService.getOneById(key);
            if(!wQbdQualitymanage.getFlowStatus().equals(FlowStatusEnum.NOT_SUBMIT.getValue()) && StringUtil.isNotEmpty(wQbdQualitymanage.getFlowStatus())){
                ProcessRun processRun = processRunService.getByBusinessKey(key);
                if(processRun!=null){
                    processRunService.deleteByProcessRun(processRun);
                }
            }
        }
        int result = wQbdQualitymanageService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转到质量管理体系导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdQualitymanage/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到质量管理体系导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdQualitymanage.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出质量管理体系数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: sun
     * @date: 2020-05-06 15:57:36
     */
    @RequestMapping("/exportData")
    @Action(description = "导出质量管理体系数据信息", detail = "导出质量管理体系数据信息<#if success>成功<#else></#if>")
    public void exportData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdQualitymanage> wQbdQualitymanages = this.wQbdQualitymanageService.queryAll(queryFilter);
        if (wQbdQualitymanages.isEmpty()) {
            wQbdQualitymanages.add(new WQbdQualitymanage());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdQualitymanages, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 导入资源文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                if ("fTrialdeptnameid".equals(fieldName)) {
                    returnType = new ReturnType();
                    // 受审核部门,当数据库中存在此部门时，才允许导入
                    List<SysOrg> sysOrgs = sysOrgService.queryByOrgName(fieldValue);
                    if (sysOrgs.size() == 0) {
                        returnType.setMsg("不存在此组织");
                    } else {
                        SysOrg sysOrg = sysOrgs.get(0);
                        returnType.setNewValue(sysOrg.getCode());
                    }
                } else if ("fAccordingstandar".equals(fieldName)) {
                    // 依据标准，当数据库中存在此依据标准时，才允许导入
                    QueryFilter queryFilter = new QueryFilter(request);
                    queryFilter.clear();
                    queryFilter.addFilter("accordingStandard", fieldValue);
                    List<WQbdAccordingStandard> wQbdAccordingStandards = wQbdAccordingStandardService.queryList(queryFilter);
                    if (wQbdAccordingStandards.size() == 0) {
                        returnType = new ReturnType();
                        returnType.setMsg("不存在此标准");
                    }
                } else if ("fStandardclause".equals(fieldName)) {
                    // 标准条款，当数据库中存在此标准条款时，才允许导入
                    QueryFilter queryFilter = new QueryFilter(request);
                    queryFilter.clear();
                    queryFilter.addFilter("standardClause", fieldValue);
                    List<WQbdStandardClause> wQbdStandardClauses = wQbdStandardClauseService.queryList(queryFilter);
                    if (wQbdStandardClauses.size() == 0) {
                        returnType = new ReturnType();
                        returnType.setMsg("不存在此标准条款");
                    }
                } else if ("fStandardcontent".equals(fieldName)) {
                    // 标准内容，当数据库中存在此标准内容时，才允许导入
                    QueryFilter queryFilter = new QueryFilter(request);
                    queryFilter.clear();
                    queryFilter.addFilter("standardClauseContent", fieldValue);
                    List<WQbdStandardClause> wQbdStandardClauses = wQbdStandardClauseService.queryList(queryFilter);
                    if (wQbdStandardClauses.size() == 0) {
                        returnType = new ReturnType();
                        returnType.setMsg("不存在此标准内容");
                    }
                } else if ("fSubstandardclauses".equals(fieldName)) {
                    // 子标准条款，当数据库中存在此子标准条款时，才允许导入
                    QueryFilter queryFilter = new QueryFilter(request);
                    queryFilter.clear();
                    queryFilter.addFilter("subStandardClause", fieldValue);
                    List<WQbdSubStandardClause> wQbdSubStandardClauses = wQbdSubStandardClauseService.queryList(queryFilter);
                    if (wQbdSubStandardClauses.size() == 0) {
                        returnType = new ReturnType();
                        returnType.setMsg("不存在此子标准条款");
                    }
                } else if ("fSubstandardcontent".equals(fieldName)) {
                    // 子标准内容，当数据库中存在此子标准内容时，才允许导入
                    QueryFilter queryFilter = new QueryFilter(request);
                    queryFilter.clear();
                    queryFilter.addFilter("subStandardClauseContent", fieldValue);
                    List<WQbdSubStandardClause> wQbdSubStandardClauses = wQbdSubStandardClauseService.queryList(queryFilter);
                    if (wQbdSubStandardClauses.size() == 0) {
                        returnType = new ReturnType();
                        returnType.setMsg("不存在此子标准内容");
                    }
                }
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdQualitymanage.class);
        String msg = map.get("msg").toString();
        List<WQbdQualitymanage> list = (List<WQbdQualitymanage>) map.get("instList");
        if (StringUtil.isEmpty(msg)) {
            this.wQbdQualitymanageService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("dataSource.importXml.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(msg);
        }
    }

    /**
     * 功能描述: 跳转至modify页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/modify")
    @Action(description = "跳转到质量管理体系modify页面")
    public String viewModify(HttpServletRequest request, ModelMap modelMap, @RequestParam(value = "flowKey", required = false) String flowKey) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        modelMap.put("flowKey", flowKey);
        return "wQbdQualitymanage/modify";
    }

    /**
     * 功能描述: 跳转至detail页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/detail")
    @Action(description = "跳转到质量管理体系detail页面")
    public String viewDetail(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        return "wQbdQualitymanage/detail";
    }

    /**
     * 功能描述: 启动流程
     */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动质量管理体系流程",detail="启动流程<#if success>成功<#else></#if>")
    public Object run(HttpServletRequest request,@RequestBody WQbdQualitymanage wQbdQualitymanage){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String id = wQbdQualitymanage.getId();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd  processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("zlgltxsplc");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(isList == 1){
                wQbdQualitymanage = wQbdQualitymanageService.getOneById(id);
            }
            processCmd.setBusinessKey(id);
            processRunService.startProcess(processCmd);
            wQbdQualitymanageService.updateFlowStatus(id);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }

    /**
     * 查询上报的信息
     *
     * @param id        业务数据主键
     * @param tableName 业务表名
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(@RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdQualitymanage> reportList = wQbdQualitymanageService.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }
}
